package org.brdevils.bf2sas.server;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.brdevils.bf2sas.client.ResponseEvent;
import org.brdevils.bf2sas.client.TelnetService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TelnetServiceImpl extends RemoteServiceServlet implements
        TelnetService, ReadListener {
    private ServerConnection conn;
    private List events = new ArrayList();

    public void connect(String name) {
        conn = new ServerConnection(this);
        conn.connect(name);
    }

    public void diconnect() {
    }

    public void send(String command) {
        conn.write(command);
    }

    public List receive() {
        List theEvents = null;
        try {
            synchronized (events) {
                events.wait(30000);
            }
        } catch (InterruptedException ignored) {
        }

        synchronized (events) {
            theEvents = new ArrayList(events);
            events.clear();
        }
        return theEvents;
    }

    public void onRead(String message) {
        synchronized (events) {
            events.add(new ResponseEvent(message));
            events.notifyAll();
        }
    }

}
